//
//  ZYAudioManager.m
//  ZYAudioPlaying
//
//  Created by 王志盼 on 15/10/12.
//  Copyright © 2015年 王志盼. All rights reserved.
//

#import "ZYAudioManager.h"
#import "ZYMusicTool.h"
#import "ZYMusic.h"

@interface ZYAudioManager ()
@property (nonatomic, strong) NSMutableDictionary *musicPlayers;
@property (nonatomic, strong) NSMutableDictionary *soundIDs;
@property (nonatomic, retain) MPMusicPlayerController *mpc;

@end

static ZYAudioManager *_instance = nil;

@implementation ZYAudioManager

+ (instancetype)defaultManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

- (instancetype)init
{
    __block ZYAudioManager *temp = self;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if ((temp = [super init]) != nil) {
            _musicPlayers = [NSMutableDictionary dictionary];
            _soundIDs = [NSMutableDictionary dictionary];
            NSArray *music = [ZYMusicTool musics];
            NSMutableArray *musicList = [[NSMutableArray alloc] init];
            [music enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                ZYMusic *music = obj;
                MPMediaItem *item = music.item;
                [musicList addObject:item];
            }];
            MPMediaItemCollection *mic = [[MPMediaItemCollection alloc] initWithItems:musicList];
            self.mpc = [MPMusicPlayerController applicationMusicPlayer];
            //[self.mpc beginGeneratingPlaybackNotifications];
            [self.mpc setQueueWithItemCollection:mic];
        }
    });
    self = temp;
    return self;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

//播放音乐
- (void)playingMusic:(MPMediaItem *)item
{
    if (item == nil)  return;
    self.nowPlayItem = item;
    [self.mpc setNowPlayingItem:item];
    [self.mpc play];
}

- (void)playPauseMusic
{
    if (self.nowPlayItem == nil) return;
    MPMusicPlaybackState state = [self.mpc playbackState];
    if (state == MPMusicPlaybackStatePlaying) {
        [self.mpc pause];
    } else {
        [self.mpc play];
    }
}

- (void)stopMusic
{
    if (self.nowPlayItem == nil)  return;
    [self.mpc stop];
}

- (MPMediaItem *)nextMusic {
    [self.mpc skipToNextItem];
    [self.mpc play];
    self.nowPlayItem = self.mpc.nowPlayingItem;
    return self.nowPlayItem;
}

- (MPMediaItem *)preMusic {
    [self.mpc skipToPreviousItem];
    [self.mpc play];
    self.nowPlayItem = self.mpc.nowPlayingItem;
    return self.nowPlayItem;
}

- (void)beginMusic {
    [self.mpc skipToBeginning];
    [self.mpc play];
    self.nowPlayItem = self.mpc.nowPlayingItem;
}

- (MPMusicPlayerController *)mpcVC {
    return self.mpc;
}
@end
